<template>
  <img alt="背景" src="../assets/header.jpg" width="90%">
  <br><br><br>
  <h2 style="text-align: left;">每日精选菜谱</h2>
  <br>
  <div class="recipe-cards">
    <a-card v-for="recipe in recipes" :key="recipe.recipe_id" :bodyStyle="{ padding: '20px' }"
            @click="navigateToDetail(recipe)">
      <template #cover>
        <a-image :src="recipe.image_url" style="width: 100%;" />
      </template>
      <div class="card-title">{{ recipe.title }}</div>
      <p>{{ recipe.description }}</p>
      <div>
        <span>发布者: {{ recipe.user_id }}</span>
      </div>
    </a-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import axios from 'axios';
import { notification } from 'ant-design-vue';
import { useRouter } from 'vue-router';

// 定义食谱数据列表
const recipes = ref([]);

// 获取食谱数据
const handleFetchRecipes = () => {
  const token = localStorage.getItem('token');

  // 如果存在token，则设置请求头
  const config = {
    headers: {
      'Token': token
    }
  };

  axios.get('/recipe/lists', config)
      .then((response) => {
        const data = response.data;
        if (data.code === 0) {
          recipes.value = data.data;
        } else {
          notification.error({ description: data.message });
        }
      })
      .catch((error) => {
        notification.error({ description: '没有得到数据' + error });
      });
};

const router = useRouter();

// 导航到详情页
const navigateToDetail = (recipe) => {
  router.push({ name: 'RecipeDetail', params: { recipeId: recipe.recipe_id } });
};

// 在组件挂载时加载数据
onMounted(() => {
  handleFetchRecipes();
});
</script>

<style scoped>
.recipe-cards {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-around;
}

.recipe-cards > .ant-card {
  width: calc(33% - 20px); /* 调整为适合你的布局的宽度 */
  margin-bottom: 20px;
}

.card-title {
  /* 你可以在这里添加一些样式来确保它看起来像标题 */
  font-size: 1.25em;
  font-weight: bold;
  margin-bottom: 10px;
}

@media (max-width: 768px) {
  .recipe-cards > .ant-card {
    width: calc(50% - 20px);
  }
}

@media (max-width: 480px) {
  .recipe-cards > .ant-card {
    width: 100%;
  }
}
</style>